package com.qf.tomcat;

import com.qf.tomcat.annotation.WebServlet;
import com.qf.tomcat.exception.UriUnuniqueException;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;

public class TomcatWebServletScan {

    public HashMap<String,HttpServlet> servletScan() throws URISyntaxException,ClassNotFoundException,IllegalAccessException,InstantiationException, UriUnuniqueException{
        HashMap<String,HttpServlet> servletHashMap = new HashMap<>();
        String basePackage = "com.qf.test";
        String path = basePackage.replaceAll("\\.","/");
        URL url = TomcatWebServletScan.class.getResource("/");
        File file = new File(url.getPath()+path);
        File[] files = file.listFiles();
        for (int i = 0,size=files.length; i < size; i++){
            if (files[i].isFile()){
                String filename = files[i].getName();
                if (filename.endsWith(".class")){
                    String[] strings = filename.split("\\.");
                    String className = strings[0];
                    String allClassName = basePackage+"."+className;
                    Class<?> aClass = Class.forName(allClassName);
                    WebServlet annotation = aClass.getAnnotation(WebServlet.class);
                    if (annotation != null){
                        String uri = annotation.value();
                        if (servletHashMap.get(uri) != null){
                            throw new UriUnuniqueException("地址相同"+uri);
                        }
                        HttpServlet servlet =(HttpServlet)aClass.newInstance();
                        servletHashMap.put(uri,servlet);
                    }
                }
                     }else {

                }
            }
                  return servletHashMap;
    }
}
